<template>
  <div class="container">
    <el-card>
      <img class="logo" src="../../assets/logo.png" alt="">
        <!-- 表单 -->
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
           <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login()">登录</el-button>
        </el-form-item>
      </el-form>
      </el-card>

  </div>
</template>

<script>
// 导入utils中的auth.js
import auth from '@/utils/auth'
export default {
  name: 'LoginPage',
  data () {
    const checkMobile = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('手机号格式不对'))
      }
    }
    return {
      form: {
        mobile: '13011836256',
        code: '246810'
      },
      rules: {
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      // form表单整体校验
      this.$refs.form.validate(async vaild => {
        if (vaild) {
          // try{可能出现的错误}catch(e){执行的代码,前面出错不会影响后面代码的执行 e.response.data.message 放的是错误信息}
          try {
            // 进行登陆请求
            const res = await this.$http.post('/v1_0/authorizations', this.form)
            // console.log(res.data.data)
            // 登录成功后 保存token到本地
            // localStorage.setItem('geek-client-pc-store', res.data.data.token)
            // 使用auth.js中的设置token的方法
            auth.setToken(res.data.data.token)
            // 跳转到首页
            this.$router.push('/')
          } catch (e) {
            // 登录失败后显示错误信息
            // console.log(e.response.data.message)
            this.$message.error(e.response.data.message || '登录失败')
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  background:url('../../assets/login.png');
  .el-card{
    width: 400px;
    height: 360px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    .logo{
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    };
    .el-form{
      padding: 0 20px;
      .el-button{
        width: 100%;
      }
    }
  }
}
</style>
